package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"xixi/models"
)

type VideoController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *VideoController) Add() {
	file, header, err := c.GetFile("img")
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "请选择文件并上传",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	defer file.Close()
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	sp, _ := c.GetInt("sp")
	name := c.GetString("name")
	js := c.GetString("js")
	img := c.GetString("img")
	time := c.GetString("time")
	people := c.GetString("people")
	video := models.Video{
		Sp:     sp,
		Name:   name,
		Js:     js,
		Img:    img,
		Time:   time,
		People: people,
	}
	err = models.DB.Create(&video).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: video,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}

func (c *VideoController) List() {
	name := c.GetString("name")
	where := map[string]string{}
	if name != "" {
		where["name"] = name
	}
	err := models.DB.Find(&models.Video{}).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}

func (c *VideoController) Up() {
	id, _ := c.GetInt("id")
	sp, _ := c.GetInt("sp")
	name := c.GetString("name")
	js := c.GetString("js")
	img := c.GetString("img")
	time := c.GetString("time")
	people := c.GetString("people")
	video := models.Video{
		Id:     id,
		Sp:     sp,
		Name:   name,
		Js:     js,
		Img:    img,
		Time:   time,
		People: people,
	}
	err := models.DB.Create(&video).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: video,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}

func (c *VideoController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Video{}, id).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
